<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户昵称" prop="nickName" >
        <el-input
            v-model="queryParams.nickName"
            placeholder="请输入用户昵称"
            clearable
            @keyup.enter="handleQuery"
        />

      </el-form-item>


      <el-form-item label="就诊状态" prop="treatState" >
        <el-select
            v-model="queryParams.treatState"
            placeholder="请选择就诊状态"
            clearable
            style="width: 100px"
        >
          <el-option label="已就诊" value="已就诊"></el-option>
          <el-option label="待就诊" value="待就诊"></el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="就诊日期" prop="treatTime">
        <el-date-picker clearable
                        v-model="queryParams.treatTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        format="YYYY-MM-DD"
                        placeholder="请选择就诊日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['treatment:treatmentMessage:export']"
        >导出</el-button>
      </el-col>
      <!-- 添加视图切换按钮 -->
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            :icon="viewMode === 'card' ? 'Grid' : 'Collection'"
            @click="toggleViewMode"
        >
          {{ viewMode === 'card' ? '表格视图' : '卡片视图' }}
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格视图 -->
    <el-table
        v-if="viewMode === 'table'"
        :data="treatmentMessageList"
        v-loading="loading"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="就诊ID" align="center" prop="treatId" />-->
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="年龄" align="center" prop="userAge" />
      <el-table-column label="联系电话" align="center" prop="userPhone" />
      <el-table-column label="预约信息" align="center" prop="appInfo" />
      <el-table-column label="预约时间" align="center" prop="appDateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.appDateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="就诊状态" align="center" prop="treatState" >
        <template #default="scope">
          <span :class="getTreatStateClass(scope.row.treatState)">
            {{ scope.row.treatState }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="就诊时间" align="center" prop="treatTime" width="180">
        <template #default="scope">
          <span>{{ scope.row.treatTime ? parseTime(scope.row.treatTime, '{y}-{m}-{d} {h}:{i}:{s}') : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              link
              type="primary"
              icon="View"
              @click="handleVisit(scope.row, scope.row.treatState === '已就诊')"
          >
            {{ scope.row.treatState === '已就诊' ? '就诊记录' : '就诊' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 替换表格为卡片布局 -->
    <div v-if="viewMode === 'card'" class="card-container">
      <el-card
          v-for="item in treatmentMessageList"
          :key="item.treatId"
          class="treatment-card"
          :class="{'selected-card': selectedIds.includes(item.treatId)}"
      >

        <div class="card-header">
          <el-checkbox
              @change="handleCardSelection(item)"
              class="card-checkbox"
          ></el-checkbox>

        </div>

        <div class="card-body">
          <div class="card-row">
            <span class="card-label">用户昵称:</span>
            <span class="card-value">{{ item.nickName }}</span>
          </div>

          <div class="card-row">
            <span class="card-label">年龄:</span>
            <span class="card-value">{{ item.userAge }}</span>
          </div>

          <div class="card-row">
            <span class="card-label">联系电话:</span>
            <span class="card-value">{{ item.userPhone }}</span>
          </div>

          <div class="card-row">
            <span class="card-label">预约信息:</span>
            <span class="card-value">{{ item.appInfo }}</span>
          </div>

          <div class="card-row">
            <span class="card-label">预约时间:</span>
            <span class="card-value">{{ parseTime(item.appDateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </div>

          <div class="card-row">
            <span class="card-label">就诊状态:</span>
            <span :class="getTreatStateClass(item.treatState)" class="card-value">
              {{ item.treatState }}
            </span>
          </div>

          <div class="card-row">
            <span class="card-label">就诊时间:</span>
            <span class="card-value">{{ item.treatTime ? parseTime(item.treatTime, '{y}-{m}-{d} {h}:{i}:{s}') : '' }}</span>
          </div>

        </div>

        <div class="card-actions">
          <el-button
              link
              type="primary"
              icon="View"
              @click="handleVisit(item, item.treatState === '已就诊')"
              :class="item.treatState === '已就诊' ? 'record-button' : 'visit-button'"
          >
            {{ item.treatState === '已就诊' ? '就诊记录' : '就诊' }}
          </el-button>
        </div>

      </el-card>
    </div>


    <!-- 分页组件保持不变 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改就诊信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="treatmentMessageRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="诊断描述" prop="treatInfo">
          <el-input v-model="form.treatInfo" placeholder="请输入诊断描述" />
        </el-form-item>

        <el-form-item label="就诊状态" prop="treatState">
          <el-input v-model="form.treatState" placeholder="请输入就诊状态" />
        </el-form-item>
        <el-form-item label="就诊时间" prop="treatTime">
          <el-date-picker clearable
                          v-model="queryParams.treatTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择就诊时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>



    <!-- 就诊记录对话框 ================================================================-->
    <el-dialog title="就诊记录" v-model="visitOpen" width="800px" append-to-body>
      <el-form ref="visitFormRef" :model="visitForm" :rules="visitRules" label-width="100px">
        <!-- 用户就诊信息 -->
        <el-card class="mb-3">
          <template #header>
            <div class="card-header">
              <span>用户就诊信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户昵称">
                <!-- 根据只读模式标志决定是否禁用输入框 -->
                <el-input v-model="visitForm.nickName" disabled  />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="年龄">
                <!-- 哈哈哈哈哈哈哈LLLLL：根据只读模式标志决定是否禁用输入框 -->
                <el-input v-model="visitForm.userAge" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 获取地址在这里显示，容纳十几个字的，不用输入框-->
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="预约信息">
                <!-- 根据只读模式标志决定是否禁用输入框 -->
                <el-input v-model="visitForm.appInfo" disabled/>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 就诊信息 -->
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="就诊描述">
                <el-input
                    v-model="visitForm.treatInfo"
                    type="textarea"
                    :rows="4"
                    :disabled="visitForm.isReadOnly"
                    placeholder="请描述用户症状、诊断结果及治疗建议..." />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 药品清单 =================================================================-->
        <el-card class="mb-3">
          <template #header>
            <div class="card-header d-flex justify-content-between align-items-center">
              <span>药品清单</span>
              <!-- 只有在非只读模式下才显示添加药品按钮 -->
              <el-button v-if="!visitForm.isReadOnly" type="primary" @click="addMedicine" size="small">
                <i class="el-icon-plus"></i> 添加药品
              </el-button>
            </div>
          </template>
          <el-table :data="visitForm.medicines" style="width: 100%">

            <el-table-column label="药品类型" width="180">
              <template #default="scope">
                <el-select
                    v-model="scope.row.drugType"
                    placeholder="请选择药品类型"
                    style="width: 100%"
                    :disabled="visitForm.isReadOnly"
                    @change="handleDrugTypeChange(scope.row)">
                  <el-option
                      v-for="(item, index) in getMedicineTypes()"
                      :key="index"
                      :label="item"
                      :value="item" />
                </el-select>
              </template>
            </el-table-column>


            <el-table-column label="药品名称" width="200">
              <template #default="scope">
                <el-select
                    v-model="scope.row.medicineId"
                    placeholder="请选择药品"
                    style="width: 100%"
                    :disabled="visitForm.isReadOnly"
                    @change="handleMedicineChange(scope.row)"
                    :loading="scope.row.loading">
                  <el-option
                      v-for="item in scope.row.medicineOptions || []"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>


            <el-table-column label="数量" width="200">
              <template #default="scope">
                <el-input-number
                    v-model="scope.row.quantity"
                    :min="1"
                    :disabled="visitForm.isReadOnly"
                    size="small"
                    @change="calculateTotal" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <!-- 哈哈哈哈哈哈哈LLLLL：只有在非只读模式下才显示删除按钮 -->
                <el-button
                    v-if="!visitForm.isReadOnly"
                    type="danger"
                    icon="Delete"
                    circle
                    size="small"
                    @click="removeMedicine(scope.$index)" />
                <!-- 在只读模式下显示占位符 -->
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table>

        </el-card>

      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visitOpen = false">取 消</el-button>
          <!-- 只有在非只读模式下才显示提交按钮 -->
          <el-button v-if="!visitForm.isReadOnly" type="primary" @click="submitVisitForm">提交就诊记录</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="TreatmentMessage">
import { listTreatmentMessage, getTreatmentMessage, delTreatmentMessage, addTreatmentMessage, updateTreatmentMessage } from "@/api/treatment/treatmentMessage"

import {submitTreatmentRecord} from "@/api/treatment/treatmentMessage";
import {listAllMedicines} from "@/api/treatment/treatmentMessage";
import {getPrescriptionMedicines} from "@/api/treatment/treatmentMessage";
import {listMedicineStocksByType} from "@/api/treatment/treatmentMessage";

const { proxy } = getCurrentInstance()
const { medicine_type } = proxy.useDict('medicine_type')
const treatmentMessageList = ref([])
const open = ref(false)
const visitOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const medicineOptions = ref([])
const isReadOnly = ref(false)


// 添加视图模式，默认为表格视图，从本地存储获取或使用默认值
const viewMode = ref(localStorage.getItem('treatmentViewMode') || 'table')

// 切换视图模式
function toggleViewMode() {
  viewMode.value = viewMode.value === 'card' ? 'table' : 'card'
  // 保存用户选择到本地存储
  localStorage.setItem('treatmentViewMode', viewMode.value)
}


// 药品数据（按类型分类）
const medicineDataByType = ref({})

// 模拟药品数据（实际项目中应该从后端获取）
const medicineData = []



const data = reactive({
  form: {},
  visitForm: {
    prescriptId: null,
    treatId: null,
    nickName: "",
    userName: "",
    userAge: null,
    userGender: "",
    userPhone: "",
    appInfo: "",
    appDateTime: "",
    treatTime: "",
    treatState: "",
    treatInfo: "",
    medicines: [],
    totalPrice: 0,
    isReadOnly: false

  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    nickName: null,
    treatInfo: null,
    // prescriptId: null,
    treatState: null,
    treatTime: null
  },
  rules: {
    nickName: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" },
    ],
// 添加就诊记录表单的校验规则
    visitRules: {
      treatInfo: [
        { required: true, message: "就诊信息不能为空", trigger: "blur" }
      ]
    }
  }
})

const { queryParams, form, rules, visitForm } = toRefs(data)

/** 查询就诊信息列表 */
function getList() {
  loading.value = true
  listTreatmentMessage(queryParams.value).then(response => {
    treatmentMessageList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    treatId: null,
    nickName: null,
    treatInfo: null,
    // prescriptId: null,
    treatState: null,
    treatTime: null,
    appInfo: null,
    appDateTime: null
  }
  proxy.resetForm("treatmentMessageRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据


// /** 新增按钮操作 */
// function handleAdd() {
//   reset()
//   open.value = true
//   title.value = "添加就诊信息"
// }
//
// /** 修改按钮操作 */
// function handleUpdate(row) {
//   reset()
//   const _treatId = row.treatId || ids.value
//   getTreatmentMessage(_treatId).then(response => {
//     form.value = response.data
//     open.value = true
//     title.value = "修改就诊信息"
//   })
// }

/** 就诊按钮操作 */
/** 就诊按钮操作 */
/** 就诊按钮操作 */
/** 就诊按钮操作 */
function handleVisit(row, isReadOnly = false) {
  // 设置只读模式标志
  visitForm.value.isReadOnly = isReadOnly;

  // 将用户信息填充到就诊表单中
  visitForm.value.treatId = row.treatId
  visitForm.value.nickName = row.nickName
  visitForm.value.userName = row.userName
  visitForm.value.userAge = row.userAge
  visitForm.value.appInfo = row.appInfo
  visitForm.value.appDateTime = row.appDateTime
  visitForm.value.treatInfo = row.treatInfo

  visitForm.value.medicines = []

  // 预加载所有药品数据并按类型分类
  loadAllMedicinesByType().then(() => {
    // 处理处方药品
    if (row.prescriptId) {
      loadPrescriptionMedicines(row.prescriptId).then(() => {
        // 如果就诊记录中已有药品清单，则加载这些药品
        if (row.yaoDans && Array.isArray(row.yaoDans)) {
          visitForm.value.medicines = row.yaoDans.map(item => ({
            drugType: item.drugType || '',
            medicineId: item.drugId || null,
            name: item.name || '',
            quantity: item.quantity || 1,
            drugId: item.drugId || null
          }))
        }
        visitOpen.value = true;
      });
    } else {
      // 如果就诊记录中已有药品清单，则加载这些药品
      if (row.yaoDans && Array.isArray(row.yaoDans)) {
        visitForm.value.medicines = row.yaoDans.map(item => ({
          drugType: item.drugType || '',
          medicineId: item.drugId || null,
          name: item.name || '',
          quantity: item.quantity || 1,
          drugId: item.drugId || null
        }))
      }
      visitOpen.value = true;
    }
  }).catch(error => {

    proxy.$modal.msgError('加载药品数据失败');
    visitOpen.value = true;
  });
}





// 预加载所有药品数据
// 预加载所有药品数据
// 预加载所有药品数据
// 预加载所有药品数据
// 预加载所有药品数据
// 预加载所有药品数据
// ... existing code ...
// ... existing code ...
// ... existing code ...
async function loadAllMedicinesByType() {
  console.log('开始加载药品数据...');

  // 如果已经有数据，不需要重新加载
  if (medicineDataByType.value && Object.keys(medicineDataByType.value).length > 0) {
    console.log('使用缓存的药品数据:', medicineDataByType.value);
    return Promise.resolve();
  }

  try {
    // 使用新的按类型分组接口
    console.log('调用 listMedicineStocksByType API');
    const response = await listMedicineStocksByType();
    console.log('API响应:', response);

    // 检查响应及响应数据是否存在
    if (!response || !response.data) {
      console.warn('药品数据为空或？？？格式不正确');
      medicineDataByType.value = {};
      return Promise.resolve();
    }

    console.log('从后端获取的药品数据:', response.data);

    // 确保 medicineDataByType 是一个响应式对象
    if (!medicineDataByType.value) {
      medicineDataByType.value = {};
    }

    // 处理后端返回的数据，过滤掉数字键，只保留类型键
    const filteredData = {};

    // 确保 response.data 是对象类型再进行处理
    if (typeof response.data === 'object' && !Array.isArray(response.data)) {
      Object.keys(response.data).forEach(key => {
        // 只处理字符串类型的键（药品类型），忽略数字索引
        if (isNaN(key) && Array.isArray(response.data[key])) {
          filteredData[key] = response.data[key];
        }
      });
    }

    medicineDataByType.value = filteredData;

    console.log('药品数据已从后端加载并缓存:', medicineDataByType.value);
    return Promise.resolve();
  } catch (error) {
    proxy.$modal.msgError('药品数据加载失败');
    medicineDataByType.value = {}; // 确保在出错时也初始化为空对象
    return Promise.reject(error);
  }
}
// ... existing code ...

// ... existing code ...

// ... existing code ...








//     ：根据处方ID加载处方药品信息
//     ：根据处方ID加载处方药品信息
//     ：根据处方ID加载处方药品信息
async function loadPrescriptionMedicines(prescriptId) {
  // 啊啊啊还要查询：这里假设后端提供根据处方ID获取药品清单的接口
  // 啊啊啊还要查询：如果后端支持该接口，请根据实际接口修改

  try {
    const response = await getPrescriptionMedicines(prescriptId);
    if (response && response.data) {
      // 啊啊啊还要查询：处理处方绑定的药品信息
      console.log('处方绑定的药品:', response.data);
      // 将后端返回的药品数据转换为表格所需格式//药品清单
      const prescriptionMedicines = response.data.map(item => ({
        drugType: item.drugStyleName || item.drugType || '', // 药品类型需要额外获取或选择
        medicineId:  item.name || null,
        name: item.name || '',
        quantity: item.quantity || 1,
        drugId: item.drugId  || null
      }));

      // 将处方药品添加到药品清单中
      visitForm.value.medicines = [...prescriptionMedicines];

      // 啊啊啊还要查询：可以在这里更新药品表单或其他相关操作
    }
  } catch (error) {
    console.warn('获取处方药品信息失败:', error);
  }
}


// ... existing code ...





/** 药品类型变化时更新药品选项 */
/** 药品类型变化时更新药品选项 */
/** 药品类型变化时更新药品选项 */
/** 药品类型变化时更新药品选项 */
function handleDrugTypeChange(row) {
  // 根据药品类型更新药品选项  检查当前行的药品类型(row.drugType)是否已选择，且在medicineDataByType中是否存在对应类型的药品数据
  console.log('选择的药品类型:', row.drugType);
  console.log('当前药品数据:', medicineDataByType.value);

  // 确保 medicineDataByType.value 存在
  if (!medicineDataByType.value) {
    console.warn('medicineDataByType.value 未定义');
    row.medicineOptions = [];
    return;
  }

  if (row.drugType && medicineDataByType.value[row.drugType]) {
    // 更新当前行的药品选项
    row.medicineOptions = medicineDataByType.value[row.drugType];
    console.log('设置药品选项:', row.medicineOptions);
  } else {
    row.medicineOptions = [];
    console.log('未找到对应的药品选项，可用的药品类型:', Object.keys(medicineDataByType.value));
  }

  // 清空已选择的药品
  row.medicineId = null;
  row.name = "";
  row.spec = "";
  row.price = 0;
  calculateTotal();
}








/** 添加药品 */
function addMedicine() {
  visitForm.value.medicines.push({
    drugType: "",
    medicineId: null,
    name: "",
    quantity: 1
  })
}

/** 移除药品 */
function removeMedicine(index) {
  visitForm.value.medicines.splice(index, 1)
  calculateTotal()
}
/** 药品选择变化 */
/** 药品选择变化 */
function handleMedicineChange(row) {
  console.log('药品选择变化:', row);
  const selectedMedicine = (row.medicineOptions || []).find(med => med.id === row.medicineId);

  if (selectedMedicine) {
    row.name = selectedMedicine.name;
    // 保存药品ID
    row.drugId = selectedMedicine.id;
    console.log('选中药品:', selectedMedicine);
  } else {
    row.name = "";
    console.log('未找到选中药品');
  }
  calculateTotal();
}

// 辅助函数：安全地获取药品类型列表

function getMedicineTypes() {
  try {
    const types = Object.keys(medicineDataByType.value || {});
    return types;
  } catch (error) {
    console.warn('获取药品类型时出错:', error);
    return [];
  }
}



/** 计算总价 */
function calculateTotal() {
  visitForm.value.totalPrice = visitForm.value.medicines.reduce((total, medicine) => {
    return total + (medicine.price * medicine.quantity)
  }, 0).toFixed(2)
}


const submitLoading = ref(false)

const drugId= ref( null)


/** 提交就诊记录=========================================================== */
// ... existing code ...
function submitVisitForm() {
  console.log("开始执行提交操作");

  // 如果正在提交中，则阻止重复提交
  if (submitLoading.value) {
    proxy.$modal.msgWarning("数据正在处理中，请勿重复提交");
    console.log("阻止重复提交");
    return;
  }

  // 添加校验：就诊描述不能为空
  if (!visitForm.value.treatInfo || visitForm.value.treatInfo.trim() === '') {
    proxy.$modal.msgWarning("请填写就诊描述");
    console.log("就诊描述为空，阻止提交");
    return;
  }

  // 添加校验：药品清单校验
  if (visitForm.value.medicines && visitForm.value.medicines.length > 0) {
    // 检查是否有填写了数量但未选择药品的项目
    const invalidMedicine = visitForm.value.medicines.find(medicine =>
        medicine.quantity > 0 && (!medicine.drugType || !medicine.medicineId)
    );

    if (invalidMedicine) {
      proxy.$modal.msgWarning("请完善药品信息");
      console.log("药品信息不完整，阻止提交");
      return;
    }

    // 过滤掉数量为0的药品项，只提交有数量的药品
    const validMedicines = visitForm.value.medicines.filter(medicine => medicine.quantity > 0);

    // 检查是否有药品库存不足的情况
    const insufficientMedicine = validMedicines.find(medicine => {
      // 查找对应药品的库存信息
      const medicineStock = (medicine.medicineOptions || []).find(
          option => option.id === medicine.medicineId
      );

      // 添加详细的调试信息
      console.log("药品库存检查详情:", {
        药品名称: medicine.name,
        需求数量: medicine.quantity,
        药品库存信息: medicineStock,
        库存数量: medicineStock?.inventory,
        是否有库存信息: !!medicineStock,
        是否有库存数量: !!(medicineStock?.inventory),
        比较结果: medicineStock && medicine.quantity > (medicineStock.inventory || 0)
      });

      // 检查库存是否充足
      if (!medicineStock) {
        console.log("未找到药品库存信息");
        // 如果没有库存信息，我们不能确定是否有足够库存，可以选择阻止提交或允许提交
        // 这里选择允许提交，让后端处理库存检查
        return false;
      }

      if (medicineStock.inventory === undefined || medicineStock.inventory === null) {
        console.log("药品库存数量未定义");
        // 库存数量未定义，允许提交让后端处理
        return false;
      }

      return medicine.quantity > medicineStock.inventory;
    });

    if (insufficientMedicine) {
      const msg = `药品 "${insufficientMedicine.name}" 库存不足，请联系管理员`;
      proxy.$modal.msgWarning(msg);
      console.log("药品库存不足，阻止提交:", msg);
      return;
    }
  } else {
    // 药品清单为空的情况
    proxy.$modal.msgWarning("请添加药品清单");
    console.log("药品清单为空，阻止提交");
    return;
  }

  console.log("所有校验通过，准备发送请求");

  // 所有校验通过后，才执行提交操作
  // 设置提交状态为加载中
  submitLoading.value = true;

  // 构造药品清单对象
  const yaoDan = visitForm.value.medicines
      .filter(medicine => medicine.quantity > 0)
      .map(medicine => ({
        name: medicine.name,
        drugId: medicine.medicineId,
        quantity: medicine.quantity
      }));

  // 构造要发送给后端的数据对象
  const submitData = {
    treatId: visitForm.value.treatId,
    nickName: visitForm.value.nickName,
    userName: visitForm.value.userName,
    userAge: visitForm.value.userAge,
    appInfo: visitForm.value.appInfo,
    appDateTime: visitForm.value.appDateTime,
    treatInfo: visitForm.value.treatInfo,
    yaoDan: yaoDan
  };

  console.log('提交的数据:', submitData);

  // 发送请求
  submitTreatmentRecord(submitData).then(
      response => {
        console.log('提交成功:', response);
        proxy.$modal.msgSuccess("提交成功");
        visitOpen.value = false;
        getList();

        // 设置标记，提示药品库存页面需要刷新
        localStorage.setItem('medicineStocksNeedRefresh', 'true');

        // 只有当药品清单有数据时才提示库存更新
        if (yaoDan && yaoDan.length > 0) {
          // 立即提示用户药品库存将被更新
          proxy.$modal.msgSuccess("相关药品库存将自动更新");
        }
      },
      error => {
        // 检查是否是库存不足的错误
        if (error && error.message && error.message.includes("库存不足")) {
          proxy.$modal.msgError("药品库存不足，请联系管理员");
        } else {
          proxy.$modal.msgError("提交失败");
        }
      }
  ).finally(() => {
    submitLoading.value = false;
  })
}
// ... existing code ...

// ... existing code ...

// ... existing code ...


// 将实际的提交逻辑分离到独立的函数中
function executeSubmit() {
  // 设置提交状态为加载中
  submitLoading.value = true;

  // 构造药品清单对象
  const yaoDan = visitForm.value.medicines
      .filter(medicine => medicine.quantity > 0)
      .map(medicine => ({
        name: medicine.name,
        drugId: medicine.medicineId,
        quantity: medicine.quantity
      }));

  // 构造要发送给后端的数据对象
  const submitData = {
    treatId: visitForm.value.treatId,
    nickName: visitForm.value.nickName,
    userName: visitForm.value.userName,
    userAge: visitForm.value.userAge,
    appInfo: visitForm.value.appInfo,
    appDateTime: visitForm.value.appDateTime,
    treatInfo: visitForm.value.treatInfo,
    yaoDan: yaoDan
  };

  console.log('提交的数据:', submitData);

  submitTreatmentRecord(submitData).then(
      response => {
        console.log('提交成功:', response);
        proxy.$modal.msgSuccess("提交成功");
        visitOpen.value = false;
        getList();

        // 设置标记，提示药品库存页面需要刷新
        localStorage.setItem('medicineStocksNeedRefresh', 'true');

        // 只有当药品清单有数据时才提示库存更新
        if (yaoDan && yaoDan.length > 0) {
          // 立即提示用户药品库存将被更新
          proxy.$modal.msgSuccess("相关药品库存将自动更新");
        }
      },
      error => {
        console.warn('提交失败:', error);
        // 检查是否是库存不足的错误
        if (error && error.message && error.message.includes("库存不足")) {
          proxy.$modal.msgError("药品库存不足，请联系管理员");
        } else {
          proxy.$modal.msgError("提交失败");
        }
      }
  ).finally(() => {
    submitLoading.value = false;
  })
}


const selectedIds = ref([])
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.treatId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

// 添加卡片选择处理函数
function handleCardSelection() {
  // 空函数，保持代码完整性
}



//：添加获取就诊状态样式类的方法
function getTreatStateClass(treatState) {
  if (treatState === '待就诊') {
    return 'status-not-visited';
  } else if (treatState === '已就诊') {
    return 'status-visited';
  }
  return '';
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('treatment/treatmentMessage/export', {
    ...queryParams.value
  }, `treatmentMessage_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
.card-header {
  font-weight: 600;
  color: #409EFF;
}
.d-flex {
  display: flex;
}
.justify-content-between {
  justify-content: space-between;
}
.align-items-center {
  align-items: center;
}
.text-right {
  text-align: right;
}
.mb-3 {
  margin-bottom: 1rem;
}

.readonly-field .el-input__inner {
  background-color: #f5f7fa !important;
  color: #909399 !important;
  cursor: not-allowed !important;
}

.readonly-field .el-input__inner:hover {
  border-color: #dcdfe6 !important;
}

.readonly-field .el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa !important;
  color: #909399 !important;
  cursor: not-allowed !important;
}


.status-not-visited {
  padding: 4px 14px;
  border-radius: 16px;
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fde2e2;
  font-weight: 500;
  font-size: 10px;
  display: inline-block;
}

.status-visited {
  padding: 4px 14px;
  border-radius: 16px;
  background-color: #e6f7ee;
  color: #00b368;
  border: 1px solid #c2e1d2;
  font-weight: 500;
  font-size: 10px;
  display: inline-block;
}

.status-not-visited::before {
  content: "● ";
  font-size: 14px;
}

.status-visited::before {
  content: "● ";
  font-size: 14px;
}


.card-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.treatment-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  overflow: hidden;
  transform: scale(1);
}

.treatment-card:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
  border-color: #409eff;
}

.selected-card {
  border: 2px solid #409eff;
  box-shadow: 0 2px 12px 0 rgba(64, 158, 255, 0.3);
}

.selected-card:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 20px 0 rgba(64, 158, 255, 0.4);
}

.card-header {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #d5f3c9;
  border-bottom: 1px solid #c3d4d7;
  background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);
}



.card-id {
  margin-left: 10px;
  font-weight: 600;
  color: #606266;
}

.card-body {
  padding: 15px;
}

.card-row {
  display: flex;
  margin-bottom: 12px;
  line-height: 1.5;
}

.card-label {
  width: 80px;
  font-weight: 600;
  color: #909399;
}

.card-value {
  flex: 1;
  color: #606266;
  word-break: break-word;
}

.card-actions {
  padding: 15px;
  border-top: 1px solid #ebeef5;
  text-align: right;
}

.visit-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.visit-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(102, 126, 234, 0.4);
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
}

.record-button {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  border: none;
  color: white;
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.record-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(245, 87, 108, 0.4);
  background: linear-gradient(135deg, #f5576c 0%, #f093fb 100%);
}

.delete-button {
  margin-left: 10px;
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
  border: none;
  color: white;
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.delete-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(255, 154, 158, 0.4);
  background: linear-gradient(135deg, #fad0c4 0%, #ff9a9e 100%);
}

/* 表格中的操作按钮样式 */
.table-visit-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  font-weight: 500;
  padding: 6px 12px;
  border-radius: 15px;
  transition: all 0.3s ease;
}

.table-visit-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 3px 6px rgba(102, 126, 234, 0.4);
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
}

.table-record-button {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  border: none;
  color: white;
  font-weight: 500;
  padding: 6px 12px;
  border-radius: 15px;
  transition: all 0.3s ease;
}

.table-record-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 3px 6px rgba(245, 87, 108, 0.4);
  background: linear-gradient(135deg, #f5576c 0%, #f093fb 100%);
}

.status-not-visited {
  padding: 4px 14px;
  border-radius: 16px;
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fde2e2;
  font-weight: 500;
  font-size: 10px;
  display: inline-block;
}

.status-visited {
  padding: 4px 14px;
  border-radius: 16px;
  background-color: #e6f7ee;
  color: #00b368;
  border: 1px solid #c2e1d2;
  font-weight: 500;
  font-size: 10px;
  display: inline-block;
}

.status-not-visited::before {
  content: "● ";
  font-size: 14px;
}

.status-visited::before {
  content: "● ";
  font-size: 14px;
}

</style>
